import { getQnyConfig, getCloudFileId } from '@/api/upload.js';

/**
 * @description: 上传文件类
 * @param {object} options
 *  @value count: 上传数量
 *  @value sourceType: 来源 ['album', 'camera']
 *  @value uploadType: 上传类型 all | image | video
 *  @value savePath: 上传路径
 *  @value isNeedFileId: 是否需要返回fileId
 * @return {void}
 */
class UploadClass {
  constructor(options = {}) {
    const {
      limit = 1,
      sourceType = ['album'],
      uploadType = 'image',
      savePath = 'oa_client',
      isNeedFileId = false,
    } = options;
    // oss实例
    this.qnyOssConfig = null;
    this.successList = [];
    this.count = limit;
    this.sourceType = sourceType;
    this.uploadType = uploadType;
    this.savePath = savePath;
    this.isNeedFileId = isNeedFileId;
  }

  // 初始化
  init() {
    return new Promise(resolve => {
      // 初始化
      this.successList = [];
      // 凭证
      this.getStsToken().then(data => {
        let { domain, token, unique_key } = data;
        this.qnyOssConfig = { domain, token, unique_key };
        resolve();
      });
    });
  }

  // 获取凭证
  getStsToken() {
    return new Promise(resolve => {
      getQnyConfig().then(res => {
        if (res.code === 200) {
          resolve(res.data);
        }
      });
    });
  }

  // 选择文件
  uploadFile(config = {}) {
    return new Promise(resolve => {
      // 选择文件时携带了临时凭证
      if (config.token) {
        // 初始化
        this.successList = [];
        // 凭证
        this.qnyOssConfig = { ...config };
        this.uploadByBrowser().then(res => {
          resolve(res);
        });
      } else {
        this.init().then(() => {
          this.uploadByBrowser().then(res => {
            resolve(res);
          });
        });
      }
    });
  }

  // 上传
  uploadByBrowser() {
    return new Promise(resolve => {
      if (this.uploadType === 'image') {
        uni.chooseImage({
          count: this.count,
          sourceType: this.sourceType,
          success: res => {
            this.toQnyOssServer(res.tempFiles).then(list => {
              resolve(list);
            });
          },
        });
      } else {
        uni.chooseFile({
          count: this.count,
          sourceType: this.sourceType,
          extension: ['.docx', '.doc', '.pdf', '.png', '.jpg', '.jpeg'],
          success: res => {
            this.toQnyOssServer(res.tempFiles).then(list => {
              resolve(list);
            });
          },
        });
      }
    });
  }

  // 获取上传的文件id
  async getUploadFileId(keys) {
    const { code, data } = await getCloudFileId({ file_keys: keys });
    if (code === 200) {
      return data;
    }
  }

  // 上传到阿里云后回调
  toQnyOssServer(fileList) {
    return new Promise(resolve => {
      uni.showLoading({
        title: '上传中…',
      });
      let total = 0;
      const { domain, token, unique_key } = this.qnyOssConfig;
      const putExtra = {
        params: {},
        mimeType: null,
      };
      const config = {
        useCdnDomain: true,
        region: '',
      };
      const that = this;
      const observer = {
        next() {},
        error(err) {
          console.log(err);
          total++;
          if (total === fileList.length) {
            uni.hideLoading();
            resolve(this.successList);
          }
        },
        async complete(res) {
          // 额外的数据
          const extendData = {};
          if (that.isNeedFileId) {
            const data = await that.getUploadFileId([res.key]);
            extendData.fileId = data[0].id;
          }
          that.successList.push({
            fileName: fileList[total].name,
            fileUrl: domain + res.key,
            ...res,
            ...extendData,
          });
          total++;
          if (total === fileList.length) {
            uni.hideLoading();
            resolve(that.successList);
          }
        },
      };
      fileList.forEach(file => {
        const key = `${unique_key + this.savePath}/${file.name}`;
        const observable = qiniu.upload(file, key, token, putExtra, config);
        observable.subscribe(observer);
      });
    });
  }
}

export default UploadClass;
